package com.zhoukx.nio.grantChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class GrantChatClient {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String userName;

    // 构造器完成初始化操作
    public GrantChatClient() throws IOException {

        // 初始化选择器
        selector = Selector.open();

        // 连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));

        // 设置非阻塞
        socketChannel.configureBlocking(false);

        // 将socketChannel 注册到selector中
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 得到username
        userName = socketChannel.getLocalAddress().toString().substring(1);

            System.out.println(userName + " is OK...........");
    }

    /**
     * 向服务器发送消息
     */
    public void send(String info) {

        info = userName + " 说 :" + info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从服务器读取消息
     */
    public void readInfo() {


        try {

            // 获取管道数量
            int readChannel = selector.select();

            // 有可用通道
            if (readChannel > 0) {

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()) {

                    SelectionKey key = iterator.next();

                    // 读取判断
                    if (key.isReadable()) {

                        // 获取到socketCHannel
                        SocketChannel socketChannel = (SocketChannel) key.channel();

                        //得到一个buffer
                        ByteBuffer allocate = ByteBuffer.allocate(1024);

                        // 读取数据
                        socketChannel.read(allocate);

                        // 把缓存的数据换成字符
                        System.out.println(new String(allocate.array()));

                    }
                }
                // 删除管道防止重复操作
                iterator.remove();

            } else {
                System.out.println("没有可用通道..");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        GrantChatClient grantChatClient = new GrantChatClient();

        // 启动一个线程 每3秒,读取从服务器发送的数据
        new Thread() {

            @Override
            public void run() {

                while (true) {

                    grantChatClient.readInfo();

                    try {

                        Thread.currentThread().sleep(3000);

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }
            }
        }.start();

        //发送数据给服务器
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            grantChatClient.send(s);
        }


    }
}
